package tom_io_nio.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ByteBufferProgram {

    public static void main(String args[]) throws Exception {


        //文件io处理
        FileInputStream fileOutputStream = new FileInputStream("/Users/mac/Desktop/test.txt");
        //创建io的操作管道
        FileChannel channel = fileOutputStream.getChannel();

        //分配10个字节的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        output("初始化", byteBuffer);

        //读下
        channel.read(byteBuffer);
        output("调用read()", byteBuffer);

        //准备操作之前，先锁定操作范围
        byteBuffer.flip();
        output("调用flip()", byteBuffer);

        while (byteBuffer.remaining() > 0) {
            byte b = byteBuffer.get();
            System.out.println((char) b);
            output("调用get()", byteBuffer);
        }

        //解锁
        byteBuffer.clear();
        output("调用clear()", byteBuffer);


        channel.close();//关闭管道
    }

    //把这个缓冲里面实时状态给答应出来
    public static void output(String step, Buffer buffer) {
        System.out.println(step + " : ");
        //容量，数组大小
        System.out.print("capacity: " + buffer.capacity() + ", ");
        //当前操作数据所在的位置，也可以叫做游标
        System.out.print("position: " + buffer.position() + ", ");
        //锁定值，flip，数据操作范围索引只能在position - limit 之间
        System.out.println("limit: " + buffer.limit());
        System.out.println("-----------------------");
    }
}
